package org.wh1tew0lf.vframe.framework;

import java.util.Map;

import org.wh1tew0lf.vframe.framework.vframeexception.VFrameException;

public class VDatabaseQueryStructure {
	
	private VDatabaseRestriction restriction = null;
	private VDatabaseOrdership ordership = null;
	private String extraWhereStmt = null;
	private int structureId = -1;
	
	public VDatabaseQueryStructure(int id, VDatabaseRestriction restriction, VDatabaseOrdership ordership) {
		this.structureId = (id >= 0) ? id : -1;
		this.restriction = restriction;
		this.ordership = ordership;
	}
	
	protected void updateId(int id) {
		this.structureId = id;
	}
	
	protected VDatabaseRestriction getRestriction() {
		return this.restriction;
	}
	
	protected VDatabaseOrdership getOrdership() {
		return this.ordership;
	}
	
	protected boolean isEqualTo(VDatabaseQueryStructure another) {
		if (this.extraWhereStmt != null) {
			if (this.extraWhereStmt.equals(another.extraWhereStmt)) {
				return true;
			} else {
				return false;
			}
		}
		if (this.restriction == null) {
			if (another.restriction != null) {
				return false;
			}
		} else {
			if (!(this.restriction.isEqualTo(another.restriction, false))) {
				return false;
			}
		}
		if (this.ordership == null) {
			if (another.ordership != null) {
				return false;
			}
		} else {
			if (!(this.ordership.isEqualTo(another.ordership))) {
				return false;
			}
		}
		return true;
	}
	
	protected String toString(Map<String, String> nameMap) throws VFrameException {
		if (this.extraWhereStmt != null) {
			return this.extraWhereStmt;
		}
		StringBuffer result = new StringBuffer();
		if (this.restriction != null) {
			result.append("WHERE ").append(this.restriction.toString(false, nameMap)).append(" ");
		}
		if (this.ordership != null) {
			result.append(this.ordership.toString(false, nameMap)).append(" ");
		}
		if (result.length() > 0) {
			return result.substring(0, result.length() -1);
		} else {
			result = null;
			return "";
		}
	}
	
	public int getId() {
		return this.structureId;
	}

}
